import type { VxeGridProps, VxeGridPropTypes } from 'vxe-table';

import type { VbenFormProps, VbenFormSchema } from '#/adapter/form';
import type { DuplicateCheckQry } from '#/api/core/duplicateCheck';

import { merge } from 'lodash';

import { z } from '#/adapter/form';
import { doDuplicateCheck } from '#/api/core/duplicateCheck';
import { schemaName } from '#/api/schemaName';
import { useRequestHandle as sysPostRequest } from '#/api/system/sysPost';
import { useRequestHandle } from '#/api/system/user';
import { useDict } from '#/utils/dictUtils';

const { status, sex } = useDict('status', 'sex');

function checkDate(
  fieldVal: string,
  dataId: string,
  fieldName: string,
): DuplicateCheckQry {
  return {
    schemaName: schemaName.system, // 数据库名
    tableName: 'sys_user', // 表名
    fieldName, // 字段名
    fieldVal, // 字段值
    dataId, // 数据ID
    keyName: 'user_id', // 主键名称
  };
}
export interface SysUserRow {
  userId: string;
  username: string;
  nickname: string;
  avatar: string;
  phone: string;
  email: string;
  sex: string;
  birthday: string;
  status: string;
  createAt: string;
}
export const searchFormOptions: VbenFormProps = {
  // 默认展开
  collapsed: false,
  // 控制表单是否显示折叠按钮
  showCollapseButton: true,
  submitButtonOptions: {
    content: '查询',
  },
  // 是否在字段值改变时提交表单
  submitOnChange: false,
  // 按下回车时是否提交表单
  submitOnEnter: false,
  schema: [
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户昵称',
        clearable: true,
      },
      fieldName: 'nickname',
      label: '昵称',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入用户名',
        clearable: true,
      },
      fieldName: 'username',
      label: '用户名',
    },
    {
      component: 'Input',
      componentProps: {
        placeholder: '请输入手机号',
        clearable: true,
      },
      fieldName: 'phone',
      label: '手机号',
    },
    {
      component: 'Select',
      componentProps: {
        clearable: true,
        placeholder: '请选择',
        options: status,
      },
      fieldName: 'status',
      label: '状态',
    },
  ],
};

const columns: VxeGridPropTypes.Columns<SysUserRow> = [
  {
    field: 'userId',
    align: 'left',
    type: 'checkbox',
    width: 50,
  },
  { field: 'username', title: '用户名', width: 150 },
  { field: 'nickname', title: '昵称', width: 150 },

  { field: 'email', title: '邮箱', width: 150 },

  {
    field: 'sex',
    title: '性别',
    width: 60,
    cellRender: { name: 'Dict', props: { dict: 'sex' } },
  },
  {
    field: 'status',
    title: '状态',
    width: 50,
    cellRender: { name: 'Dict', props: { dict: 'status' } },
  },
  {
    field: 'avatar',
    title: '头像',
    width: 100,
    cellRender: { name: 'CellImage' },
  },
  {
    field: 'birthday',
    title: '生日',
    width: 150,
  },
  {
    field: 'createAt',
    title: '创建时间',
    width: 150,
  },
  {
    field: 'action',
    title: '操作',
    width: 200,
    fixed: 'right',
    slots: { default: 'action' },
  },
];

/**
 * Configuration options for the grid component.
 * @template SysUserRow - The type of data rows in the grid.
 */
export const gridOptions: VxeGridProps<SysUserRow> = {
  columns,
  proxyConfig: {
    enabled: true,
    autoLoad: true,
    ajax: {
      query: async ({ page }, formValues) => {
        return useRequestHandle.page(
          merge(
            {
              current: page.currentPage,
              pages: page.pageSize,
            },
            formValues,
          ),
        );
      },
    },
  },
  toolbarConfig: {
    enabled: true,
    // @ts-ignore 是否显示搜索表单控制按钮
    search: true,
    custom: true,
    export: true,
    // import: true,
    refresh: true,
    zoom: true,
  },
  exportConfig: {
    // 导出文件名
    filename: '用户列表',
  },
};

export const formSchema: VbenFormSchema[] = [
  {
    label: 'userId',
    fieldName: 'userId',
    component: 'Input',
    dependencies: {
      show: false,
      triggerFields: ['userId'],
    },
  },
  {
    component: 'Input',
    fieldName: 'username',
    label: '用户名',
    dependencies: {
      async rules(values) {
        const { username, userId } = values;
        if (!username) {
          return 'required';
        }
        const { pass, message } = await doDuplicateCheck(
          checkDate(username, userId, 'username'),
        );
        return z
          .string()
          .min(1, '用户名长度不能小于1')
          .max(32, '用户名长度不能大于6')
          .refine(() => pass, {
            message,
          });
      },
      triggerFields: ['username'],
    },
  },
  {
    component: 'Input',
    fieldName: 'nickname',
    label: '昵称',
    dependencies: {
      async rules(values) {
        const { nickname, userId } = values;
        if (!nickname) {
          return 'required';
        }
        const { pass, message } = await doDuplicateCheck(
          checkDate(nickname, userId, 'nickname'),
        );
        return z
          .string()
          .min(1, '昵称长度不能小于1')
          .max(6, '昵称长度不能大于6')
          .refine(() => pass, {
            message,
          });
      },
      triggerFields: ['nickname'],
    },
  },
  {
    component: 'Input',
    fieldName: 'email',
    label: '邮箱',
    dependencies: {
      async rules(values) {
        const { email, userId } = values;
        if (!email) {
          return 'required';
        }
        const { pass, message } = await doDuplicateCheck(
          checkDate(email, userId, 'email'),
        );
        return z
          .string()
          .email()
          .refine(() => pass, {
            message,
          });
      },
      triggerFields: ['email'],
    },
  },
  {
    component: 'Input',
    fieldName: 'phone',
    label: '手机号',
    dependencies: {
      async rules(values) {
        const { phone, userId } = values;
        if (!phone) {
          return 'required';
        }
        const { pass, message } = await doDuplicateCheck(
          checkDate(phone, userId, 'phone'),
        );
        return z
          .string()
          .min(11, '手机号长度不能小于1')
          .max(11, '手机号长度不能大于6')
          .refine(() => /^1[3-9]\d{9}$/, {
            message: '请输入正确的手机号格式',
          })
          .refine(() => pass, {
            message,
          });
      },
      triggerFields: ['phone'],
    },
  },
  {
    component: 'Upload',
    fieldName: 'avatar',
    label: '头像',
    componentProps: {
      accept: 'image/*',
      limit: 1,
      showFileList: true,
      listType: 'picture-card',
      uploadText: '上传头像',
      action: '/api/system/file/upload',
    },
  },
  {
    component: 'DatePicker',
    fieldName: 'birthday',
    label: '生日',
    componentProps: {
      type: 'date',
      clearable: true,
    },
  },
  {
    component: 'Select',
    fieldName: 'sex',
    label: '性别',
    componentProps: {
      clearable: true,
      placeholder: '请选择',
      options: sex,
    },
  },
  {
    component: 'Select',
    fieldName: 'status',
    label: '状态',
    componentProps: {
      clearable: true,
      placeholder: '请选择',
      options: status,
    },
  },
  {
    component: 'ApiSelect',
    fieldName: 'postIds',
    label: '岗位',
    componentProps: {
      class: 'w-full',
      props: {
        label: 'postName',
        children: 'children',
        value: 'postId',
      },
      showCheckbox: true,
      multiple: true,
      nodeKey: 'postId',
      api: async (query: any) => {
        return await sysPostRequest.list(query);
      },
    },
  },
  {
    component: 'Input',
    fieldName: 'deptIds',
    label: '所属部门',
    componentProps: {
      props: {
        label: 'deptName',
        children: 'children',
      },
      showCheckbox: true,
      multiple: true,
      nodeKey: 'deptId',
    },
  },
];
